import java.util.ArrayList;
import java.util.List;

/**
 * 观察者模式
 */
public class ObserverTest {
    public static void main(String[] args) {
        Subject subject = new Subject();
        Task1 observerAble = new Task1();
        subject.addObserver(observerAble);

        Task2 observerAble1 = new Task2();
        subject.addObserver(observerAble1);


        subject.notifyObserver("这是第一条信息");

        System.out.println("---------------------------");

        subject.deleteObserver(observerAble);

        //这里再次进行更新的时候就会发现，只有任务二进行更新了，原因是之前删除了任务一的监听
        subject.notifyObserver("这是第二条信息");
    }
}

class Subject {
    //容器
    List<ObserverAble> list = new ArrayList<>();

    //增加
    public void addObserver(ObserverAble observerAble) {
        list.add(observerAble);
    }

    //删除
    public void deleteObserver(ObserverAble observerAble) {
        list.remove(observerAble);
    }

    //提醒
    public void notifyObserver(Object object) {
        for (ObserverAble item : list) {
            item.update(object);
        }
    }
}

//定义观察接口
interface ObserverAble {
    void update(Object object);
}

class Task1 implements ObserverAble {

    @Override
    public void update(Object object) {
        System.out.println("task1 received  " + object);
    }
}

class Task2 implements ObserverAble {

    @Override
    public void update(Object object) {
        System.out.println("task2 received  " + object);
    }
}